package com.ngrok.handler;

import com.ngrok.NgrokContext;
import com.ngrok.handler.decoder.HttpResponse;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by pj on 2017/9/28.
 */
@ChannelHandler.Sharable
public class NgrokHttpHandler extends SimpleChannelInboundHandler<HttpResponse> {
    private final static Logger loger= LoggerFactory.getLogger(NgrokHttpHandler.class);
    private NgrokContext context;
//    private NettyClient localClient=new NettyClient();
    public NgrokHttpHandler( NgrokContext context){
        this.context=context;
    }

   @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext,HttpResponse httpMessage) throws Exception {
//        System.out.println(httpMessage);
        context.close(context.getRemotechannel());
        context.setRemotechannel(channelHandlerContext.channel());//更新当前远程channel
        new Thread(()->{
            context.getLocalhost(context.getConfig().getApi().getData().get(0).getProto().getHttp(),context.getConfig().getApi().getData().get(0).getProto().getProt()).writeAndFlush(Unpooled.copiedBuffer(httpMessage.getResponseByte()));
        }).start();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
